<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="关键词" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键词"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="直播分类" prop="liveType">
        <el-select
          v-model="queryParams.typeId"
          placeholder="请选择直播分类"
          clearable
        >
          <el-option
            v-for="item in liveTypeList"
            :key="item.typeId"
            :label="item.typeName"
            :value="item.typeId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >添加直播</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-paperclip"
          size="mini"
          @click="bulkImport"
        >批量导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-document"
          size="mini"
          @click="batchExport"
        >批量导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="urlId" />
      <el-table-column label="图标" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="直播名称" align="center" prop="name" />
      <el-table-column label="直播地址" align="center" prop="displayUrl" />
      <el-table-column label="分类" align="center" prop="typeName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import {addLive, delLive, listLive, updateLive} from "@/api/media/live/list";
import CryptoJS from 'crypto-js';

import 'crypto-js/aes';
import 'crypto-js/mode-ecb';
import 'crypto-js/pad-pkcs7';
import liveTypeList from "@/views/media/live/type/LiveTypeList.vue";
import {listLiveType} from "@/api/media/live/type/list";

export default {
  name: "LiveList",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      tableList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        typeId: null,
        keyword: null,
      },
      form: {},
      displayUrl:'',
      typeName:'',
      rules: {
      },
      liveTypeList:[],
      exportUrl: null,
      exportPassword: null,
    }
  },
  created() {
    this.getList();
    this.getLiveTypes();
  },

  methods: {

    // 获取所有的直播分类
    getLiveTypes() {
      listLiveType(this.queryParams).then(response => {
        this.liveTypeList = response.rows;
      }).catch(error => {
        this.$message.error('加载分类数据失败');
      });
    },

    getList() {
      this.loading = true;

      listLive(this.queryParams).then(response => {
        this.tableList = response.rows.map(item => {

          const decryptedUrl = this.decryptUrl(item.url, 'TP25076786123456');
          const decryptedPassword = this.decryptUrl(item.password, 'TP25076786123456');

          const cleanedUrl = decryptedUrl.replace(/[^\x00-\x7F]/g, '');

          let formattedUrl = cleanedUrl.replace(/hd\d*:/g, ',hd:').replace(/sd\d*:/g, ',sd:');

          if (formattedUrl.startsWith(',')) {
            formattedUrl = formattedUrl.substring(1);
          }

          const urlArray = formattedUrl.match(/(hd:[^,]+|sd:[^,]+)/g) || [];

          const highQualityUrls = urlArray.filter(url => url.startsWith('hd:')).map(url => url.substring(3));
          const lowQualityUrls = urlArray.filter(url => url.startsWith('sd:')).map(url => url.substring(3));

          const truncateUrl = (urls) => {
            if (urls.length > 0) {
              return urls[0].length > 50 ? urls[0].substring(0, 50) + '...' : urls[0];
            } else {
              return '无';
            }
          };

          const highQualityStream = highQualityUrls.length > 0
            ? `高画质流--共${highQualityUrls.length}路：` + truncateUrl(highQualityUrls)
            : '';

          const lowQualityStream = lowQualityUrls.length > 0
            ? `低画质流--共${lowQualityUrls.length}路：` + truncateUrl(lowQualityUrls)
            : '';

          item.displayUrl = `${highQualityStream}\n${lowQualityStream}`;
          item.exportUrl =  decryptedUrl
          item.exportPassword = decryptedPassword
          return item;
        });

        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        this.loading = false;
      });
    },

    decryptUrl(encryptedUrl, password) {
      try {
        const key = CryptoJS.enc.Utf8.parse(password);

        const encryptedUrlParts = encryptedUrl.split(',');

        const decryptedUrlParts = encryptedUrlParts.map(part => {
          const encryptedBytes = CryptoJS.enc.Base64.parse(part);

          // 解密每个部分
          const decryptedBytes = CryptoJS.AES.decrypt({ ciphertext: encryptedBytes }, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7,
          });

          const decryptedText = decryptedBytes.toString(CryptoJS.enc.Utf8);

          if (!decryptedText) {
            return decryptedBytes.toString(CryptoJS.enc.Base64);  // 返回 Base64 编码的字符串
          }

          return decryptedText;
        });

        return decryptedUrlParts.join('');
      } catch (e) {
        return '';
      }
    },

    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        image: null,
        url: null,
        password: null,
        typeId: null,
        urlId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.typeId = null;

      this.resetForm("queryForm");

      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ name: 'create' }).catch(err => {
        console.error('路由跳转错误:', err);
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({ name: 'edit', params: { id: row.id } }).catch(err => {
        console.error('路由跳转错误:', err);
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除直播频道编号为"' + ids + '"的数据项？').then(function() {
        return delLive(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 批量导入 **/
    bulkImport(){
      var userConfirmed = confirm("是否需要批量导入列表？这会代替原来的列表内容，是否继续？");

      if (userConfirmed) {
        // 跳转二级路由
        this.$router.push({ name: 'liveBulkImport' }).catch(err => {
          console.error('路由跳转错误:', err);
        });
      } else {

      }
    },
    /** 批量导出 **/
    batchExport(){
        const selectedData = this.ids.length > 0 ? this.tableList.filter(item => this.ids.includes(item.id)) : this.tableList;

        if (selectedData.length === 0) {
          this.$message.error("请先选择数据项！");
          return;
        }

        const data = selectedData.map(item => {
          return [
            item.urlId,
            item.name,
            item.exportUrl,
            item.exportPassword,
          ].join(",");
        });

        // 将数据转换为字符串
        const content = data.join("\n");

        // 创建Blob对象
        const blob = new Blob([content], { type: "text/plain;charset=utf-8" });

        // 创建下载链接
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "live.txt";

        // 触发点击事件下载文件
        link.click();

    }
  }
};
</script>
